﻿using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Drawing;
using System.Drawing.Imaging;
using ICSharpCode.SharpZipLib;
using ICSharpCode.SharpZipLib.Zip;
using ICSharpCode.SharpZipLib.Zip.Compression;

namespace QuickTools.MatchmediaHelper
{
    public static class Utils
    {
        /// <summary>
        /// Determines the mod played given the game's main <paramref name="path"/> by looking at the last modified date of the keyFile
        /// inside the subdirectories of the game's <paramref name="path"/>
        /// </summary>
        /// <param name="path"></param>
        /// <param name="keyFile"></param>
        /// <returns></returns>
        public static string GetModFromDir(string path, string keyFile)
        {
            string mod = string.Empty;
            DateTime LastWriteAccess = DateTime.MinValue;
            DirectoryInfo[] dirs = new DirectoryInfo(path).GetDirectories();
            foreach (DirectoryInfo d in dirs)
            {
                FileInfo keyInfo = new FileInfo(Path.Combine(d.FullName, keyFile));
                if (keyInfo.Exists)
                {
                    if (keyInfo.LastWriteTime > LastWriteAccess)
                    {
                        mod = d.Name;
                        LastWriteAccess = keyInfo.LastWriteTime;
                    }
                }
            }
            return mod;
        }

        public static string CompressFile(string file)
        {
            return CompressFile(file, Path.GetFileName(file));
        }

        public static string CompressFile(string file, string targetname)
        {
            string tmpPath = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString());
            if (!Directory.Exists(tmpPath))
            {
                Directory.CreateDirectory(tmpPath);
            }
            targetname = Path.ChangeExtension(Path.GetFileName(targetname), ".zip");
            string filePath = Path.Combine(tmpPath, targetname);
            byte[] buffer = new byte[4096];
            using (ZipOutputStream s = new ZipOutputStream(File.Create(filePath)))
            {
                // set to highest compression
                s.SetLevel(9);
                ZipEntry entry = new ZipEntry(Path.GetFileName(file));
				entry.DateTime = DateTime.Now;
				s.PutNextEntry(entry);
					
				using ( FileStream fs = File.OpenRead(file) ) {
					int sourceBytes;
					do {
						sourceBytes = fs.Read(buffer, 0, buffer.Length);
						s.Write(buffer, 0, sourceBytes);
					} while ( sourceBytes > 0 );
				}
            }
            return filePath;
        }

        public static string GetTemporaryJpeg(string origFile, int quality)
        {
            ImageCodecInfo myImageCodecInfo = GetEncoderInfo("image/jpeg");
            System.Drawing.Imaging.Encoder myEncoder = System.Drawing.Imaging.Encoder.Quality;

            // EncoderParameter object in the array.
            EncoderParameters encoderParams = new EncoderParameters(1);
            // Save the bitmap as a JPEG file with quality level 25.
            encoderParams.Param[0] = new EncoderParameter(myEncoder, quality);

            string tmpFile = System.IO.Path.GetTempPath() + Guid.NewGuid().ToString() + ".jpg";
            try
            {
                using (Image img = Image.FromFile(origFile))
                {
                    img.Save(tmpFile, myImageCodecInfo, encoderParams);
                }
            }
            catch (Exception)
            {
                File.Delete(tmpFile);
                throw;
            }

            return tmpFile;
        }

        private static ImageCodecInfo GetEncoderInfo(String mimeType)
        {
            int j;
            ImageCodecInfo[] encoders;
            encoders = ImageCodecInfo.GetImageEncoders();
            for (j = 0; j < encoders.Length; ++j)
            {
                if (encoders[j].MimeType == mimeType)
                    return encoders[j];
            }
            return null;
        }

        
    }
}
